<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传者" prop="uploadBy">
        <el-input
          v-model="queryParams.uploadBy"
          placeholder="请输入上传者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间" prop="uploadTime">
        <el-date-picker clearable
                        v-model="queryParams.uploadTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择上传时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['file:info:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['file:info:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['file:info:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['file:info:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="上传者" align="center" prop="uploadBy"/>
      <el-table-column label="文件名称" align="center" prop="fileName"/>
      <el-table-column label="文件分类" align="center" prop="categoryName"/>

      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件权限" align="center" :formatter="filePermission" prop="permission"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; gap: 8px;  white-space: nowrap; ">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['file:info:edit']"
            >修改
            </el-button>
            <template>
              <div>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="fileVisible(scope.row)"
                  v-hasPermi="['file:info:preview']"
                >预览
                </el-button>
              </div>
            </template>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="fileUpload(scope.row)"
              v-hasPermi="['file:info:remove']"
            >下载
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['file:info:remove']"
            >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件分类" prop="idCategory">
          <el-select v-model="form.idCategory" placeholder="选择分类">
            <el-option
              v-for="dv in selectCategoryName"
              :key="dv.categoryId"
              :label="dv.categoryName"
              :value="dv.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
         <div v-show="isAdd" >
           <el-form-item label="文件上传" prop="file" >
             <el-upload
               class="upload-demo"
               action="http://localhost:8080/common/minio/upload"
               :on-preview="handlePreview"
               :on-success="handleAvatarSuccess"
               :on-remove="handleRemove"
               :before-remove="beforeRemove"
               :limit="1"
                accept=".docx,.pdf,.excel "
               :on-exceed="handleExceed"
               :file-list="fileList">
               <el-button size="small" type="primary" >点击上传</el-button>
               <div slot="tip" class="el-upload__tip">只能上传docx,pdf,excel文件，且不超过10MB</div>
             </el-upload>
           </el-form-item>
         </div>
        <el-form-item label="权限" prop="permission">
          <el-select v-model="form.permission" placeholder="私密或分享">
            <el-option
              v-for="di in yesNoPermission"
              :key="di.value"
              :label="di.label"
              :value="di.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end;">
        <el-button type="primary" size="small" @click="submitForm" style="margin-right: 10px;">确 定</el-button>

        <el-button @click="cancel" size="small" style="margin-right: 10px;">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="预览文件" width="60%" :visible.sync="dialogVisible" center>
      <vue-office-docx
        :src="currentFileUrl"
        v-if="fileType === 'docx'"
      />
      <vue-office-pdf
        style="height: 75vh"
        :src="currentFileUrl"
        v-else-if="fileType === 'pdf'"
      />
      <VueOfficeExcel
        style="height: 75vh"
        :src="currentFileUrl"
        v-else-if="fileType === 'xlsx'"
      />
      <div v-else>
      只预览支持 .docx .pdf .excel 文件的预览
     </div>
    </el-dialog>

  </div>
</template>


<script>
import {listInfo, getInfo, delInfo, addInfo, updateInfo, getCategory} from "@/api/file/info"
import {downloadFileToMinio} from "@/utils/fileutils/fileUtils";
import VueOfficeDocx from "@vue-office/docx";
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'
import VueOfficePdf from "@vue-office/pdf";
import VueOfficeExcel from "@vue-office/excel";

export default {
  name: "info",
  components: {
    VueOfficeExcel,
    VueOfficePdf,
    VueOfficeDocx
  },
  data() {
    return {
      // 文件类型
      fileType:'',
      // 显示弹窗
      dialogVisible: false,
      // 文件id
      fileId: null,
      // 是否对话框显示文件
      isAdd: true,
      // 实现文件上传验证的临时变量
      file: null,
      // 上传文件名
      uploadFileName: null,
      // 控制是否显示预览组件
      isShowPreview: false,
      // 文件地址
      currentFileUrl: null,
      // 文件上传
      fileList: [],
      // 设置权限
      yesNoPermission: [
        {label: '分享', value: 1},
        {label: '私密', value: 0}
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出
      open: false,
      // 分类名
      selectCategoryName: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileSize: null,
        fileType: null,
        fileCategory: null,
        uploadBy: null,
        uploadTime: null,
        status: null,
        permission: null,
      },
      // 表单参数
      form: {file:null},
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "用户名不为空", trigger: "blur"}
        ],
        idCategory: [
          {required: true, message: "分类不为空", trigger: "blur"}
        ],
        permission: [
          {required: true, message: "权限不为空", trigger: "blur"}
        ],
        file:[
          {required: true, message: "文件不为空", trigger: 'change'}
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getCategoryName()
  },
  methods: {
    // 文件下载
    fileUpload(row){
      const match = row.currentFileUrl.match(/\/\/[^/]+\/[^/]+\/(.*)/);
      const remoteFileName= match ? match[1] : '';
      downloadFileToMinio(remoteFileName,row.fileName)
    },
    /**文件上传名字与路径和 大小返回**/
    handleAvatarSuccess(res, file) {
      this.$set(this.form, 'file', file)//使Vue 响应式触发
      this.currentFileUrl = res.data.url;
      this.form.currentFileUrl = this.currentFileUrl
      this.uploadFileName = file.name
      this.form.fileName=this.uploadFileName
      this.$nextTick(() => {
        //等待更新完成,清空旧的file值
        if (this.$refs.form) {
          this.$refs.form.clearValidate('file');
        }
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 获取文件分类
    getCategoryName() {
      getCategory().then(response => {
        // 获取后端的文件分类
        this.selectCategoryName = response.data
      })
    },
    // 显示文件权限
    filePermission(row) {
      return row.permission === 0 ? '私密' : '公开';
    },
    /** 查询文件信息列表 */
    getList() {
      this.loading = true
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        fileName: null,
        fileSize: null,
        fileType: null,
        uploadBy: null,
        uploadTime: null,
        updateBy: null,
        updateTime: null,
        status: null,
        delFlag: null,
        remark: null,
        fileCategory: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection)
    {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isAdd = true
      this.fileList = []
      this.reset()
      this.open = true
      this.title = "添加文件信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isAdd = false
      this.reset()
      const fileId = row.fileId || this.ids
      this.fileList = []
      this.fileList.push({name: this.uploadFileName, url: this.currentFileUrl})
      getInfo(fileId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改文件信息"
      })

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid =>{
        if (valid) {
          if (this.form.fileId != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids
      this.$modal.confirm('是否确认删除文件信息编号为"' + fileIds + '"的数据项？').then(function () {
        return delInfo(fileIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('file/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    /** 预览文件*/
    fileVisible(row) {
      this.dialogVisible = true
      let lastIndex = row.currentFileUrl.lastIndexOf('.');
      this.fileType = lastIndex === -1 ? '' : row.currentFileUrl.substring(lastIndex + 1);
      this.currentFileUrl = row.currentFileUrl
    },
  }
}
</script>

